package com.xiangyun.auth.config.service;

import java.util.List;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xiangyun.auth.dao.TSysRoleMenuPermissionMapper;
import com.xiangyun.auth.model.TSysRoleMenuPermissionVO;
import com.xiangyun.auth.model.TSysUser;
import com.xiangyun.auth.service.TUserService;

@Service
public class UserDetailsServiceImpl implements UserDetailsService{
	
	@Autowired
	private TUserService tUserService;
	
	@Autowired
	private TSysRoleMenuPermissionMapper menuPermissionService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		System.out.println("成功进入了认证服务器的密码授权流程");
		TSysUser tUser = new TSysUser();
		tUser.setUserName(username);
		tUser = tUserService.selectByTUser(tUser);
		List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
		if(null != tUser) {
			List<TSysRoleMenuPermissionVO> permission = menuPermissionService.selectVOListByPrimaryKey(tUser.getRoleId());
			permission.forEach(TPermission ->{
				if(null != TPermission && null != TPermission.getPermission()) {
					GrantedAuthority GrantedAuthority = new SimpleGrantedAuthority(TPermission.getPermission());
					grantedAuthorities.add(GrantedAuthority);
				}
			});
		}
		
		return new User(tUser.getUserName(),tUser.getPassWord(),grantedAuthorities);
	}

}
